import React from 'react';
import {
    ChevronDownIcon,
    ChevronUpIcon,
    HStack,
    Icon,
    Image,
    Pressable,
    Text,
    View
} from "@gluestack-ui/themed";
import ChannelDownMenu from "./ChannelDownMenu";
import LineChart from "./LineChart";
import {DataPanelInterface, DataPanelProps} from "@/components/data-panel/type";
import {CalendarPopup, Icon as KIcon} from "@/components/k-view";
import {useQuery, useTheme} from "@/hooks";
import {useImmer, useImmerReducer} from "use-immer";
import * as columns from "@/theme/enums/columns";
import {popupReducer} from "@/reducers";
import {dateScreenList, channelMaps} from "@/theme/enums/screen";
import {ChooseDatePopup} from "@/components/choose-date";
import useTool from "@/utils";
import {Option} from "@/types/public";
import {fillTime} from "@/utils/modules/format";
import {useStore} from "@/store";
import {CustomColumnsPopup, CustomColumnsReducer} from "@/components/custom-columns-popup";
import {fetchCols} from "@/services/public";
import DataSwiperRequest from "@/components/data-panel/DataSwiperRequest";

const DataPanel = React.forwardRef<DataPanelInterface, DataPanelProps>((props, ref) => {
    const {colors} = useTheme();
    const {getDateRange, formatDate} = useTool();
    const channel = useStore.use.channel();

    const {
        api,
        name,
        chartApi,
        valueKey = "field",
        ...attrs
    } = props;
    const panelName = channelMaps[channel] + name;

    const [{
        loading,
        selectDate,
        dataColumns,
        selectFields,
        curField,
        refreshKey,
        showChart
    }, updateData] = useImmer({
        dataColumns: new Array<any>(),
        selectFields: new Array<string>(),
        curField: "cost",
        showChart: false,
        selectDate: "0day",
        refreshKey: 1,
        loading: false,
    });


    const [showChooseDate, dispatch] = useImmerReducer(popupReducer, false);
    const [showCalendar, calendarDispatch] = useImmerReducer(popupReducer, false);
    const [showCustomColumns, customColumnsDispatch] = useImmerReducer(popupReducer, false);
    // 所有列
    const allCols = React.useMemo(() => columns[panelName], [panelName]);
    // 选中的日期label展示
    const selectDateLabel = React.useMemo(() => {
        let option = dateScreenList.find(item => (item.value + item.unit) === selectDate);
        return option?.label ?? selectDate.split('~').map(date => formatDate(date, "MM-DD")).join('至');
    }, [selectDate]);

    // 获取自定义列请求
    let {data: colRes, isSuccess, isLoading, isFetching} = useQuery(fetchCols, {
        channel,
        fields_type: panelName,
    });
    // 获取日期范围
    const report_time_range = selectDate.indexOf("~") >= 0 ? selectDate : getDayRange(selectDate);
    let selectColumns = (colRes && colRes.data) ? echoCols(colRes.data.split(',')) : getDefaultColumns();
    React.useEffect(() => {
        if (!showChart) {
            reset();
        }
    }, [showChart]);
    React.useEffect(() => {
        updateData(draft => {
            draft.loading = true;
        })
        if (isSuccess) {
            updateData(draft => {
                draft.dataColumns = selectColumns;
                draft.loading = false;
            })
        }
    }, [isSuccess, isFetching])
    React.useImperativeHandle(ref, () => ({
        refresh: refreshPanel
    }));

    function refreshPanel() {
        updateData(draft => {
            draft.refreshKey = new Date().getTime();
        })
    }

    function reset(v = "") {
        updateData(draft => {
            draft.curField = v;
            draft.selectFields = v ? [v] : [];
        });
    }

    // 获取默认列
    function getDefaultColumns() {
        return allCols.filter((item: any) => item.default);
    }

    // 提取数字和其余字符串
    function extractNumberAndString(str: string) {
        const regex = /(-?\d+(?:\.\d+)?)([\D]+)/;
        const result = str.match(regex);

        if (result) {
            const number = result[1];
            const string = result[2];
            return [number, string];
        }

        return null;
    }

    // 获取选中的时间段
    function getDayRange(v: string) {
        let [value, unit] = extractNumberAndString(v) as string[];
        let dateRange = getDateRange(parseInt(value), unit);
        return dateRange.join("~");
    }

    function openChooseDate() {
        dispatch({
            type: "open"
        });
    }

    // 获取映射label
    function getLabelMaps() {
        return allCols.reduce((prv: Record<string, string>, cur: Record<string, string>) => {
            prv[cur[valueKey]] = cur.label;
            return prv;
        }, {})
    }

    function handleChange(f: string) {
        updateFields(f);
    }

    // 更新选中字段
    function updateFields(f: string) {
        let index = getBeforeIndex();
        let has = selectFields.findIndex(item => item == f);

        if (has >= 0) return;
        updateData(draft => {
            switch (index) {
                case -1:
                    draft.selectFields[0] = f;
                    break;

                default:
                    let i: number = index ? 0 : 1;
                    draft.selectFields[i] = f;
            }
            draft.curField = f;
        })
    }

    // 获取上次更新选中的列
    function getBeforeIndex() {
        return selectFields.findIndex((item) => item == curField)
    }

    // 打开图表
    function handleOpenChart() {
        let field = dataColumns[0][valueKey];
        updateFields(field);
        updateData(draft => {
            draft.showChart = !showChart;
        });
    }

    // 处理日历选中日期
    function handleCalendarConfirm(dates: string[]) {
        if (dates.length) {
            updateData(draft => {
                draft.selectDate = fillTime(dates).join("~");
            });
        }
    }

    // 处理选中日期变化
    function handleChooseDate(item?: Option) {
        if (!!item) {
            updateData(draft => {
                let curDate = item.value + item.unit;
                draft.selectDate = curDate;
            });
        } else {
            calendarDispatch({
                type: 'open',
            });
        }

    }

    // 处理自定义列确认
    function handleColConfirm(cols: string[]) {
        fetchCols({
            channel,
            fields_type: panelName,
            fields: cols.join()
        }).then(res => {
            updateData(draft => {
                draft.dataColumns = echoCols(cols);
            })
            if (!selectFields.every(k => cols.includes(k))) reset(cols[0]);
        });
    }

    // 将选中字符串列回显为对象
    function echoCols(cols: string[]) {
        let list: any[] = []
        cols.forEach(item => {
            let i = allCols.findIndex((col: any) => col[valueKey] == item);
            if (i >= 0) {
                list.push(allCols[i]);
            }
        });
        return list;
    }

    if (isLoading) return null;

    return (
        <>
            <View
                key={refreshKey}
                bg={"white"}
                borderRadius={14}
                {...attrs}
            >
                <View
                    h={275}
                    mb={10}
                    mx={10}
                >
                    <HStack
                        alignItems={"center"}

                    >
                        <ChannelDownMenu></ChannelDownMenu>
                        <Pressable
                            ml={"auto"}
                            mr={10}
                            onPress={openChooseDate}
                        >
                            <HStack
                                h={28}
                                px={10}
                                borderRadius={6}
                                bg={"#F8F9FA"}
                                alignItems={"center"}
                            >
                                <Text color={"$textLight400"} size={"xs"}>{selectDateLabel}</Text>
                                <KIcon
                                    name={'\ue627'}
                                    size={12}
                                    color={colors.textLight400}
                                />
                            </HStack>

                        </Pressable>

                        <Pressable onPress={() => customColumnsDispatch({type: "open"})}>
                            <HStack
                                h={28}
                                px={10}
                                borderRadius={6}
                                bg={"#F8F9FA"}
                                alignItems={"center"}
                                space={"xs"}

                            >
                                <Image mt={2} alt={"自定义"} w={"$3"} h={"$3"}
                                       source={require('@/theme/assets/images/icon/edit_icon.png')}></Image>
                                <Text color={"$textLight400"} size={"xs"}>自定义</Text>

                            </HStack>
                        </Pressable>

                    </HStack>

                    {
                        !loading &&
                        <DataSwiperRequest
                            api={api}
                            params={{
                                report_time_range,
                                channel
                            }}
                            valueKey={valueKey}
                            disabled={!showChart}
                            activeFields={selectFields}
                            list={isFetching ? [] : dataColumns}
                            sliceNum={6}
                            onChange={handleChange}
                        ></DataSwiperRequest>
                    }

                </View>
                {
                    !loading &&
                    <LineChart
                        show={showChart}
                        api={chartApi}
                        params={{
                            chart_field: selectFields,
                            report_time_range,
                            channel
                        }}
                        labelMaps={getLabelMaps()}
                    ></LineChart>
                }
                <Pressable mt={"$3"} onPress={handleOpenChart}>
                    <HStack
                        justifyContent={"center"}
                        alignItems={"center"}
                    >
                        <Text size={"sm"}
                              color={"$textLight500"}>{showChart ? '收起' : '展开'}趋势图</Text>
                        <Icon as={showChart ? ChevronUpIcon : ChevronDownIcon} w="$4" h="$4"
                              color={"$textLight500"}/>
                    </HStack>
                </Pressable>
            </View>
            <ChooseDatePopup
                isVisible={showChooseDate}
                dispatch={dispatch}
                onChange={handleChooseDate}
            ></ChooseDatePopup>

            <CalendarPopup
                dispatch={calendarDispatch}
                isVisible={showCalendar}
                onConfirm={handleCalendarConfirm}
            ></CalendarPopup>

            <CustomColumnsPopup
                title={"自定义数据指标"}
                valueKey={valueKey}
                columns={allCols}
                value={dataColumns}
                dispatch={customColumnsDispatch}
                isVisible={showCustomColumns}
                onConfirm={handleColConfirm}
            >
            </CustomColumnsPopup>
        </>
    )
})

DataPanel.displayName = "DataPanel";
export default DataPanel;